/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package terminalscontroller;

import Config.ConfigReader;
import Server.Client;
import Server.EventReceiver;
import Server.ClientListener;
import java.io.IOException;
import java.net.Socket;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

/**
 *
 * @author Administrador
 */

public class TerminalsController implements EventReceiver{

    static Vector estados = null;    
    static JSONObject jEstados = null;
    
    static String subscriptioBusHost = "localhost";
    static int subscriptioBusSubscriptionPort = 4000;
    static int listeningPort = 4001;    
    static String listeningHost = "localhost";   
    static String terminalsHost = "localhost";
    static int teminalsPortBegginingAt = 7000;
    
    
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {        
        
    try {
            // vemos en qué puerto escucha el listener
           subscriptioBusSubscriptionPort = ConfigReader.getInt("SubscriptionBusSubscriptionPort");
           listeningPort = ConfigReader.getInt("listeningPort");
           subscriptioBusHost = ConfigReader.getString("SubscriptionBusHost");
           listeningHost = ConfigReader.getString("listeningHost");
           teminalsPortBegginingAt = ConfigReader.getInt("terminalsPortBegginingAt");
           terminalsHost = ConfigReader.getString("terminalsHost");
           
           System.out.println("subscriptionBusHost: " + subscriptioBusHost);
           System.out.println("subscriptionBusSubscriptionPort: " + subscriptioBusSubscriptionPort);

           System.out.println("listeningPort: " + listeningPort);
           System.out.println("listeningHost: " + listeningHost);
           
           System.out.println("teminalsPortBegginingAt: " + teminalsPortBegginingAt);
           System.out.println("terminalsHost: " + terminalsHost);
           
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
        }
         
        // el listener recibe el estado de un vuelo
        ClientListener listener = null;
        try {
            listener = new ClientListener(listeningPort, new TerminalsController());
        } catch (IOException ex) {
            Logger.getLogger(TerminalsController.class.getName()).log(Level.SEVERE, null, ex);
        }
        // suscribimos al bus de eventos
        subscribeToEventBus();
        // empezamos a escuchar por eventos
        listener.start();
        
        jEstados = new JSONObject();
    }

    public void receiveMessage(String strMessage, Socket socket) {
        try {
        	System.out.println(strMessage);
            // Lo unico que hacemos aquí es redistribuir el mensaje a las
            // terminales, que se supone están en la misma red que el controller.
            storeFlightState(strMessage);
        } catch (Exception ex) {
            Logger.getLogger(TerminalsController.class.getName()).log(Level.SEVERE, null, ex);
        }
        sendFlightStates();        
    }
       
    private static void subscribeToEventBus() {

        Client c = new Client(subscriptioBusHost, subscriptioBusSubscriptionPort);        
        JSONObject petition = new JSONObject();
        try {
            petition.put("url", listeningHost);
            petition.put("port", listeningPort);
            c.sendNoResponseMessage(petition.toString());
        } catch (Exception ex) {
            Logger.getLogger(TerminalsController.class.getName()).log(Level.SEVERE, null, ex);
        }        
    }

    private void sendFlightStates() {
      for(int i=0; i<2; i++){
           try {
                Client c = new Client(terminalsHost, teminalsPortBegginingAt+i);            
                System.out.println("Sending status to terminal number" + i);
                c.sendNoResponseMessage(jEstados.toString());
                c.close();
                c = null;
            } catch (IOException ex) {
                System.out.println("Unable to connect to terminal " + i + ", no big deal.");
            }            
        }    
    }

    private void storeFlightState(String strMessage) throws Exception {
        
        JSONObject s = new JSONObject(strMessage);
        s = s.getJSONObject("FlightState");
        
        int id = s.getInt("flightId");               
        String nombre = "f"+id;
        // si ya había un estado con este nombre
        if(jEstados.has(nombre))
            jEstados.remove(nombre);
        jEstados.put(nombre, s);
    }   

}
